const express = require('express')
const { query } = require('../utils/pool')
const { getCondition } = require('../utils/tools')
const router = express.Router()

// 处方列表
router.get('/list', async (req, res, next) => {
  const obj = req.query
  if (!obj.pno) obj.pno = 1
  if (!obj.count) obj.count = 10
  const size = parseInt(obj.count)
  const start = (obj.pno - 1) * size
  // 用于拼接查询条件
  const newObj = { ...obj }
  delete newObj.pno
  delete newObj.count

  try {
    let sql
    if (obj.oid || obj.doctor || obj.state) {
      const condition = getCondition(newObj)
      console.log(condition)
      sql = `select * from ih_order ${condition} limit ?,?;select count(*) as n from ih_order ${condition}`
    } else {
      sql =
        'select * from ih_order limit ?,?;select count(*) as n from ih_order'
    }
    var result = await query(sql, [start, size])
  } catch (err) {
    return next(err)
  }
  res.send({
    code: 200,
    msg: '处方列表',
    data: result[0],
    total: result[1][0].n,
    pages: Math.ceil(result[1][0].n / size),
    pno: obj.pno
  })
})
// 处方药品列表
router.get('/medicine_list', async (req, res, next) => {
  const { id } = req.query
  try {
    var result = await query(
      `select a.id,b.title,b.pic
    ,a.dose,a.usage from ih_order_medicine as a,ih_medicine as b where a.mid=b.id and order_id=?;`,
      [id]
    )
  } catch (err) {
    return next(err)
  }
  console.log(result)
  res.send({
    code: 200,
    msg: '处方药品信息',
    data: result
  })
})
router.put('/verify', async (req, res, next) => {
  const obj = req.body
  try {
    var result = await query('update ih_order set ? where id=?', [
      { ...obj, verify: 1 },
      obj.id
    ])
  } catch (err) {
    return next(err)
  }
  console.log(result)
  if (result.changedRows === 0) {
    res.send({ code: 400, msg: '审核失败' })
  } else {
    res.send({ code: 200, msg: '审核成功' })
  }
})

module.exports = router
